//
// Viewer.java
//
package com.photoexpert;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.TransferHandler;

class Viewer extends JScrollPane {

    static Viewer Instance() {
        if(_instance == null)
            _instance = new Viewer();
        return _instance;
    }

    void showRuler(boolean show) {
        setColumnHeaderView(show ? Ruler.getHRuler() : null);
        setRowHeaderView(show ? Ruler.getVRuler() : null);
    }

    /* ------------------------------------------------------------------- */

    private static class Corner extends JComponent {
        @Override
        public void paint(Graphics g) {
            g.setColor(Presentor.Instance().getBackground());
            g.fillRect(0, 0, getWidth(), getHeight());
        }
    }

    private TransferHandler th = new TransferHandler() {
        @Override
        public boolean canImport(TransferHandler.TransferSupport support) {
            if (!support.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
                return false;
            return true;
        }
        @Override
        public boolean importData(TransferHandler.TransferSupport support) {
            if (!canImport(support)) {
                return false;
            }
            Transferable t = support.getTransferable();
            try {
                Implementor.Instance().closeFile();
                java.util.List<File> l =
                    (java.util.List<File>)t.getTransferData(DataFlavor.javaFileListFlavor);
                for (File f : l) {
                    Implementor.Instance().openFile(f);
                    break;
                }
            } catch (UnsupportedFlavorException e) {
                return false;
            } catch (IOException e) {
                return false;
            }
            return true;
        }
    };

    private Viewer() {
        super(Presentor.Instance());
        Ruler hRuler = Ruler.getHRuler();
        Ruler vRuler = Ruler.getVRuler();
        setPreferredSize(new Dimension(800, 600));
        hRuler.setPreferredWidth(getMaximumSize().width);
        vRuler.setPreferredHeight(getMaximumSize().height);
        setViewportBorder(BorderFactory.createLineBorder(Color.black));
        setColumnHeaderView(hRuler);
        setRowHeaderView(vRuler);
        setCorner(JScrollPane.UPPER_LEFT_CORNER, new Corner());
        setCorner(JScrollPane.LOWER_LEFT_CORNER,  new Corner());
        setCorner(JScrollPane.UPPER_RIGHT_CORNER,  new Corner());
        setTransferHandler(th);
    }

    private static Viewer _instance = null;
}
